package oa.web.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import oa.biz.DepartmentBiz;
import oa.biz.EmployeeBiz;
import oa.entity.Department;
import oa.entity.Employee;

@Controller
@Transactional(timeout=60)
@RequestMapping("/admin")
public class EmployeeController {
	@Autowired
	private EmployeeBiz employeeBiz;
	@Autowired
	private DepartmentBiz departmentBiz;
	@RequestMapping("/EmployeeList")
	public String employeeList(Model model){
		model.addAttribute("employee",employeeBiz.getAll());
		return "EmployeeList";
	}
	@RequestMapping("/newEmployee")
	public String newEmployee(Model model){
		model.addAttribute("department",departmentBiz.getAll());
		return "newEmployee";
	}
	@RequestMapping("/employeeEdit")
	public String employeeEdit(int id,Model model){
		model.addAttribute("employee",employeeBiz.fetchByid(id));
		model.addAttribute("department",departmentBiz.getAll());
		return "employeeEdit";	
	}
	
	@RequestMapping("/employeeSave")
	public String employeeSave(@RequestParam(name="id",defaultValue="0",required=false)int id,Employee employee,@RequestParam(name="myIcon",required=false)MultipartFile myIcon,HttpServletRequest request) throws IOException{
		if(id==0){
			employeeBiz.addEmployee(employee);
		}else{
			employeeBiz.updateEmployee(employee);
			
		}
		if(!myIcon.isEmpty()){
			String filename = request.getSession().getServletContext().getRealPath("/static/userIcon/"+employee.getNr()+".jsp");
			FileOutputStream fos=new FileOutputStream(filename);
			fos.write(myIcon.getBytes());
			fos.flush();
			fos.close();
		}
		
		return "redirect:EmployeeList";
	}
	
	@RequestMapping("/getEmployee")
	@ResponseBody
	public List<Employee> getEmployee(){
		return employeeBiz.getAll();
	}

}
